package com.codes.controller;

import com.codes.core.common.enumtype.RoleType;
import com.codes.core.common.enumtype.WorkOrderState;
import com.codes.core.common.result.Result;
import com.codes.core.utils.NubmerUtil;
import com.codes.core.utils.excel.ExcelUtil;
import com.codes.model.OrderInfo;
import com.codes.model.WorkOrder;
import com.codes.service.LogisticsSV;
import com.codes.service.OrderInfoSV;
import com.codes.service.WorkOrderSV;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Date 2020/5/26 10:27
 * @Created by peanut
 */
@RestController
@RequestMapping("/workorder")
@Validated // 参数校验
@Api(tags = "需求工单模块")
public class WorkOrderCtr  extends BaseController{

    @Autowired
    private WorkOrderSV workOrderSV;
    @Autowired
    private OrderInfoSV orderInfoSV;
    @Autowired
    private LogisticsSV logisticsSV;


    /**
     * @param map `start_time` datetime DEFAULT NULL COMMENT '收货开始时间',
     *            `end_time` datetime DEFAULT NULL COMMENT '收货结束时间',
     *            `confirm_time` datetime DEFAULT NULL COMMENT '确认收货时间',
     *            `is_delete` int(11) DEFAULT '0' COMMENT '是否删除 0 (假,未删) 1 真',
     *            `performance` varchar(50) DEFAULT NULL COMMENT '完成度(工单完成多少)',
     *            `remark` varchar(255) DEFAULT '' COMMENT '备注信息',
     *            `floor` varchar(255) DEFAULT '' COMMENT '楼层',
     *            `tower_crane` varchar(255) DEFAULT NULL COMMENT '塔吊',
     *            `order_type` int(11) DEFAULT '0' COMMENT '0 日计划 1 周 2 月',
     * @return
     */
    @PostMapping("/saveOrder")
    @ApiOperation(value = "新增需求工单及详情")
    @DynamicParameters(name = "CreateOrderMapModel", properties = {
            @DynamicParameter(name = "projectId", value = "1"),
            @DynamicParameter(name = "startTime", value = "2020-05-23 11:30:00"),
            @DynamicParameter(name = "endTime", value = "2020-05-23 11:30:00"),
            @DynamicParameter(name = "remark", value = "备注信息"),
            @DynamicParameter(name = "floor", value = "6楼"),
            @DynamicParameter(name = "towerCrane", value = "2号塔吊"),
            @DynamicParameter(name = "workOrderInfo", value = "{\"workOrderInfo\":[{\"productId\":1,\"count\":\"一瓶\"},{\"productId\":2,\"count\":\"两瓶\"}]} "),
    })
    public Result saveOrderInfo(@RequestBody Map<Object, Object> map) {
        List<Map<String, Object>> listMap = (ArrayList) map.get("workOrderInfo");

        if (listMap.size() == 0 || map.isEmpty()) {
            return Result.failed("请传入工单的构建详情信息: json数组对象", map);
        }
        // java 8 fore
        // listMap.forEach(map1 -> orderInfoSV.insertByMap(map1));
        int re = workOrderSV.insertByMap(map);
        if (re > 0) {
            return Result.success(map);
        }
        return Result.failed();
    }

    @ApiOperation("保存日计划,及物流单详情")
    @PostMapping("/save-order-day")
    public Result saveOrderDay(@RequestBody Map<String,Object> map){
        List<Map<String,Object>> wuliu = (ArrayList)map.get("logisticsInfo");
        if (wuliu.size() == 0 || map.isEmpty()) {
            return Result.failed("工单保存失败,数据为空", map);
        }
        workOrderSV.saveOrderDay(map);
        return  Result.success("工单保存成功");
    }

    @ApiOperation("保存周 , 月计划,及物流单详情")
    @PostMapping("/save-order-week-month")
    public Result saveOrderWeekMonth(@RequestBody Map<String,Object> map){
        List<Map<String,Object>> wuliu = (ArrayList)map.get("orderInfoWMList");
        if (wuliu.size() == 0 || map.isEmpty()) {
            return Result.failed("工单保存失败,数据为空", map);
        }
        workOrderSV.saveOrderWeekMonth(map);
        return  Result.success("工单保存成功");
    }

    @ApiOperation("接口入参:此接口只做参数说明")
    @PostMapping("/map")
    @DynamicParameters(name = "CreateOrderMapModel", properties = {
            @DynamicParameter(name = "WorkOrder", value = "订单信息", dataTypeClass = WorkOrder.class),
            @DynamicParameter(name = "OrderInfos", value = "订单详情", dataTypeClass = OrderInfo.class),
    })
    public Result saveOrder(@RequestBody Map<Object, Object> map) {
        WorkOrder workOrder = (WorkOrder) map.get("WorkOrder");
        int re = workOrderSV.insertSelective(workOrder);
        System.out.println(1);
        return Result.success(map);
    }



    @ApiOperation("获取工单list")
    @GetMapping("/list")
    public Result getList(@RequestParam Map<String, Object> map) {


        // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> orders = workOrderSV.getList(map);//

        return Result.success("获取工单列表成功", orders);

    }

    @ApiOperation("获取工单分页")
    @GetMapping("/page")
    public Result getPage(@RequestParam(defaultValue = "1", required = true) int page,
                          @RequestParam(defaultValue = "10", required = true) Integer limit,
                          @RequestParam Map<String, Object> map) {

        page = MapUtils.getInteger(map,"page");
        limit = MapUtils.getInteger(map,"limit");
        PageHelper.startPage(page, limit);
        // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> users = workOrderSV.getList(map);//
        PageInfo<Map<String, Object>> info = new PageInfo<>(users);
        return Result.pages(info.getList(), (int) info.getTotal());

    }
    @ApiOperation(" 工单分页 合并数据 ")
    @GetMapping("/page-pc")
    public Result getPagePc(@RequestParam(defaultValue = "1", required = true) int page,
                          @RequestParam(defaultValue = "10", required = true) Integer limit,
                          @RequestParam Map<String, Object> map) {


        PageHelper.startPage(page, limit);
        // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> users = workOrderSV.getListDayExport(map);
        PageInfo<Map<String, Object>> info = new PageInfo<>(users);
        return Result.pages(info.getList(), (int) info.getTotal());

    }


    @ApiOperation("根据ID获取工单详情")
    @GetMapping("/get/{id}")
    public Result getById(@ApiParam(name = "需求工单id", value = "1", required = true) @PathVariable String id) {

        try {
            System.out.println(id);
            Map<String, Object> map = workOrderSV.getById(Integer.parseInt(id));
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("获取工单详情失败", e.getMessage());
        }

    }

    @ApiOperation("获取工单 周 月 计划 详情")
    @GetMapping("/get-info-w-m")
    public Result getInfoWM(@RequestParam Map<String, Object> map){

        Integer workOrderId = MapUtils.getInteger(map,"workOrderId");
        if(null != workOrderId){
            Map<String,Object> reMap = workOrderSV.getInfoWM(workOrderId);

            return  Result.success("获取工单 周 月 计划 详情",reMap);
        }

        return Result.failed("详情获取失败");
    }

    @ApiOperation("工单审核或修改")
    @PostMapping("/audit")
    public Result auditOrder(@RequestBody Map<String, Object> map) {
        try {
            int re = workOrderSV.updateOrderDay(map);

            if (0 == re) return Result.failed("工单信息修改失败", re);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("工单信息修改失败", e.getMessage());
        }
        return Result.success("工单审核成功", 0);
    }

    @PostMapping("/del")
    @ApiOperation("删除工单by id")
    public Result deleteById(Integer id) {
        System.out.println(id);
        int re = workOrderSV.deleteByPrimaryKey(id);
        if (re > 0) {
            return Result.success();
        }
        return Result.failed("工单删除失败");
    }




    @ApiOperation("报告汇总")
    @PostMapping("/total")
    public Result getTotal(@RequestBody Map<String,Object> map){


        int total = 0;
        int finish = 0;
        String baifenbi = "";
        List<Map<String, Object>> orderList = null;
        total = getC(1001);
        finish = getC(1002);
        baifenbi = NubmerUtil.baifenbi(finish, total);
//        Integer isFinish = 0;  // 0 已完成  1 未完成
//        isFinish = MapUtils.getInteger(map, "isFinish");
        orderList = workOrderSV.getList(map);
        Map reMap = new HashMap();
        reMap.put("total", total);
        reMap.put("finish", finish);
        reMap.put("baifenbi", baifenbi);
        reMap.put("orderList", orderList);
        return  Result.success("ok",reMap);
    }

    @ApiOperation("工单汇总分页")
    @GetMapping("/total-page")
    public Result getTotalPage(@RequestParam(defaultValue = "1", required = true) int page,
                          @RequestParam(defaultValue = "10", required = true) Integer limit,
                          @RequestParam Map<String, Object> map) {

        int total = 0;
        int finish = 0;
        String baifenbi = "";



//        page = MapUtils.getInteger(map,"page");
//        limit = MapUtils.getInteger(map,"limit");
        //   -1  所有  0 未完成  1 已完成
        map.put("isF",-1);
        total = workOrderSV.getTotalListCount(map);
        map.put("isF",1);
        finish = workOrderSV.getTotalListCount(map);
        baifenbi = NubmerUtil.baifenbi(finish, total);
        PageHelper.startPage(page, limit);
        List<Map<String, Object>> users = workOrderSV.getTotalList(map);//
        PageInfo<Map<String, Object>> info = new PageInfo<>(users);
        // 封装 页面数据
        List list = info.getList();
        Map reMap = new HashMap();
        reMap.put("total", total);
        reMap.put("finish", finish);
        reMap.put("baifenbi", baifenbi);
        reMap.put("pageList",list);
        return Result.pages(reMap, (int) info.getTotal());
    }

    @ApiOperation("获取工单数量")
    @PostMapping("/count")
    public Result getCount(@RequestParam Map<String, Object> map) {

        int total = 0;
        int finish = 0;
        String baifenbi = "";
        List<Map<String, Object>> orderList = null;
        Integer isFinish = null;  // 0 已完成  1 未完成  -1 全部
         isFinish = MapUtils.getInteger(map, "isFinish");
         if(null == isFinish) isFinish = -1;
        //  角色id 来  审核不
        Integer roleType = MapUtils.getInteger(map, "roleId");
        if (null == roleType) return Result.failed("角色id无效");
        if (RoleType.planDept.getCode() == roleType) {
            // 计划 部门. 来计算 总数量
            total = getC(1001);
            finish = getC(1002);
            if (isFinish == 1) { // 计划部已完成
                orderList = getList(1001);
            }else if (isFinish == 0) {
                orderList = getList(1002);
            }else {
                orderList = getList(1003);
            }
        }
        if (RoleType.zhuchang.getCode() == roleType) {
            total = getC(1003);
            finish = getC(1004);
            // 审核部
            if (isFinish == 1) {
                orderList = getList(1003);
            } else if(isFinish == 0) {
                orderList = getList(1004);
            }else {
                orderList = getList(-1);
            }
        }
        if (RoleType.wuliu.getCode() == roleType) {
            total = logisticsSV.getCount(map);
            map.put("finishState", 2);
            finish = logisticsSV.getCount(map);
            int state = 0;
            // 物流单
            if (isFinish ==0 ) {
                //  已完成    0  未完成 1
            }else if(isFinish == 1){
                state = 1;
            }else {
                state = -1;
            }
            map.put("finishState", state);
            orderList = logisticsSV.getListByRole(map);
        }
        baifenbi = NubmerUtil.baifenbi(finish, total);
        map.put("total", total);
        map.put("finish", finish);
        map.put("baifenbi", baifenbi);
        map.put("orderList", orderList);

        return Result.success(map);
    }

    // getCount
    public int getC(int type) {
        Map m = new HashMap();
        m.put("type", type);
        return workOrderSV.getCount(m);
    }

    public  List<Map<String, Object>> getList(int type) {
        Map m = new HashMap();
        m.put("type", type);
        return workOrderSV.getListByRole(m);
    }

    // 取消订单
    @ApiOperation("取消订单")
    @PostMapping("/delete")
    public Result delete(@RequestBody  Map<String,Object> map ){
        Integer workOrderId = MapUtils.getInteger(map,"workOrderId");
        if(null == workOrderId) return  Result.failed("工单不存在");
        map.put("isDelete",1);
        int re = workOrderSV.updateByIdDel(map);
        if(re>0){
            return  Result.success("删除成功");
        }
        return  Result.failed("删除工单失败");

    }

    @ApiOperation("删除订单")
    @PostMapping("/delete-order")
    public Result deleteByid(@RequestParam  Map<String,Object> map ){
        Integer workOrderId = MapUtils.getInteger(map,"workOrderId");
        if(null == workOrderId) return  Result.failed("工单不存在");
        map.put("isDelete",1);
        int re = workOrderSV.updateByIdDel(map);
        if(re>0){
            return  Result.success("删除成功");
        }
        return  Result.failed("删除订单失败");

    }

    @ApiOperation("批量删除订单")
    @PostMapping("/delete-order-batch")
    public Result deleteByidBatch(@RequestParam  Map<String,Object> map ){
        String ids = MapUtils.getString(map,"ids");
        int re  =0;
        if(StringUtils.isNotBlank(ids)){
            String[] strs = ids.split(",");
            List<String> idss = Arrays.asList(strs) ;
            re = workOrderSV.deleteBatch(idss);
            return Result.success("删除成功");
        }
        return  Result.failed("删除失败");

    }


    @ApiOperation("导出工单日计划")
    @PostMapping("/export")
    public void exportList( HttpServletRequest request, HttpServletResponse response){
        /**
         *    projectName: $("#searchName").val().trim(),
         *             state: $("#orderState").val()
         */
        String projectName = request.getParameter("projectName");
        String stateOrder = request.getParameter("state");
        Map<String,Object> seMap = new HashMap<>();
        seMap.put("projectName",projectName);
        seMap.put("state",stateOrder);

        // 表头
        Object[] titles = new Object[]{"序号","项目名称","楼栋","楼层","负责人","工单状态","工单创建时间","规定送达时间","构件详情"};

        List<Object[]> data = new ArrayList<>();
        List< Map<String, Object>> list = workOrderSV.getListDayExport(seMap);
        Integer index =1;
        for ( Map<String, Object> m :list   ) {
            Integer state = MapUtils.getInteger(m,"state");
            String woderOrderState = WorkOrderState.getLabelByCode(state.shortValue());
            if(StringUtils.isBlank(woderOrderState)){
                woderOrderState = "";
            }

            Object[] obj = new Object[]{

                    index,
                    MapUtils.getString(m,"projectName"),
                    MapUtils.getString(m,"buildingName"),
                    MapUtils.getString(m,"floor"),
                    MapUtils.getString(m,"leaderName"),
                    woderOrderState,
                    StringUtils.substringBeforeLast(MapUtils.getString(m,"createTime"), "."), //一直找到最后一个指定的字符串
                    StringUtils.substringBeforeLast(MapUtils.getString(m,"endTime"), "."),
                    MapUtils.getString(m,"productInfo"),

            };
            data.add(obj);
            index++;
        }
        ExcelUtil.export(request,response,"列表-" + DateFormatUtils.format(new Date(), "yyyyMMdd"),titles, data);
    }

    /**
     *  并没有导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/import")
    public Result headImg(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {

        List<String[][]> list =      ExcelUtil.parseExcelData(file.getName(),file.getInputStream(),1);
        for (String[][] s : list) {
            for (int j = 0; j < s.length; j++) {
                String[] rowObject = s[j];  // 每行的数据 都是一个对象
                // 创建一个 map 来接收
                Map<String,Object> map = new HashMap<>();
                map.put("userName",rowObject[0]);
                map.put("passWord",123456);
                map.put("realName",rowObject[1]);
                String sex  =rowObject[2];
                if("男".equals(sex)){
                    map.put("sex",0);
                }else {
                    map.put("sex",1);
                }
                map.put("phone",rowObject[3]);
                map.put("dept",rowObject[4]);
                map.put("address",rowObject[5]);
              //  userService.addUser(map); // 添加用户
            }
        }
        return Result.success("导入成功");
    }

    // end
}